package com.ruoyi.ldzlsb.controller;

import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.ldzlsb.domain.SbInspectionConfig;
import com.ruoyi.ldzlsb.domain.SbInspectionItem;
import com.ruoyi.ldzlsb.service.ISbInspectionConfigService;
import com.ruoyi.ldzlsb.service.ISbInspectionItemService;

/**
 * 巡检配置Controller
 * 
 * @author anli
 * @date 2025-01-11
 */
@RestController
@RequestMapping("/inspection/config")
public class SbInspectionConfigController extends BaseController
{
    @Autowired
    private ISbInspectionConfigService sbInspectionConfigService;
    
    @Autowired
    private ISbInspectionItemService sbInspectionItemService;

    /**
     * 查询巡检配置列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SbInspectionConfig sbInspectionConfig)
    {
        startPage();
        List<SbInspectionConfig> list = sbInspectionConfigService.selectSbInspectionConfigWithTypeList(sbInspectionConfig);
        return getDataTable(list);
    }

    /**
     * 导出巡检配置列表
     */
    @PostMapping("/export")
    public void export(HttpServletResponse response, SbInspectionConfig sbInspectionConfig)
    {
        List<SbInspectionConfig> list = sbInspectionConfigService.selectSbInspectionConfigList(sbInspectionConfig);
        ExcelUtil<SbInspectionConfig> util = new ExcelUtil<SbInspectionConfig>(SbInspectionConfig.class);
        util.exportExcel(response, list, "巡检配置数据");
    }

    /**
     * 获取巡检配置详细信息
     */
    @GetMapping(value = "/{configId}")
    public AjaxResult getInfo(@PathVariable("configId") Long configId)
    {
        SbInspectionConfig config = sbInspectionConfigService.selectSbInspectionConfigByConfigId(configId);
        List<SbInspectionItem> items = sbInspectionItemService.selectSbInspectionItemByConfigId(configId);
        
        AjaxResult ajax = success(config);
        ajax.put("items", items);
        return ajax;
    }

    /**
     * 新增巡检配置
     */
    @PostMapping
    public AjaxResult add(@RequestBody Map<String, Object> params)
    {
        try {
            // 处理巡检配置基本信息
            SbInspectionConfig config = new SbInspectionConfig();
            config.setConfigName((String) params.get("configName"));
            config.setConfigCode((String) params.get("configCode"));
            
            // 正确处理设备类型ID的类型转换
            Object equipmentTypeIdObj = params.get("equipmentTypeId");
            if (equipmentTypeIdObj != null) {
                if (equipmentTypeIdObj instanceof Integer) {
                    config.setEquipmentTypeId(((Integer) equipmentTypeIdObj).longValue());
                } else if (equipmentTypeIdObj instanceof Long) {
                    config.setEquipmentTypeId((Long) equipmentTypeIdObj);
                } else if (equipmentTypeIdObj instanceof String) {
                    try {
                        config.setEquipmentTypeId(Long.parseLong((String) equipmentTypeIdObj));
                    } catch (NumberFormatException e) {
                        return error("设备类型ID格式不正确: " + e.getMessage());
                    }
                }
            }
            
            config.setCreateBy(SecurityUtils.getUsername());
            config.setRemark((String) params.get("remark"));
            config.setConfigCategory("0");  // 默认类别
            config.setConfigStatus("0");    // 默认状态：正常
            config.setIsDelete("0");        // 默认未删除
            
            // 同时设置updateBy为当前用户
            config.setUpdateBy(SecurityUtils.getUsername());
            config.setUpdateTime(new java.util.Date());
            config.setCreateTime(new java.util.Date());
            
            // 插入巡检配置，获取配置ID
            int result = sbInspectionConfigService.insertSbInspectionConfig(config);
            if (result <= 0) {
                return error("新增巡检配置失败");
            }
            
            // 处理巡检项信息
            List<Map<String, Object>> itemMaps = (List<Map<String, Object>>) params.get("items");
            if (itemMaps != null && !itemMaps.isEmpty()) {
                List<SbInspectionItem> items = new java.util.ArrayList<>();
                
                for (Map<String, Object> itemMap : itemMaps) {
                    SbInspectionItem item = new SbInspectionItem();
                    item.setItemName((String) itemMap.get("itemName"));
                    item.setItemStandard((String) itemMap.get("itemStandard"));
                    item.setRequireImage((String) itemMap.get("requireImage"));
                    items.add(item);
                }
                
                // 批量保存巡检项
                sbInspectionItemService.batchSaveInspectionItems(config.getConfigId(), items, config.getCreateBy());
            }
            
            return success();
        } catch (Exception e) {
            e.printStackTrace();
            return error("新增巡检配置失败：" + e.getMessage());
        }
    }

    /**
     * 修改巡检配置
     */
    @PutMapping
    public AjaxResult edit(@RequestBody Map<String, Object> params)
    {
        try {
            // 处理巡检配置基本信息
            SbInspectionConfig config = new SbInspectionConfig();
            
            // 处理configId的类型转换
            Object configIdObj = params.get("configId");
            if (configIdObj != null) {
                if (configIdObj instanceof Integer) {
                    config.setConfigId(((Integer) configIdObj).longValue());
                } else if (configIdObj instanceof Long) {
                    config.setConfigId((Long) configIdObj);
                } else if (configIdObj instanceof String) {
                    try {
                        config.setConfigId(Long.parseLong((String) configIdObj));
                    } catch (NumberFormatException e) {
                        return error("配置ID格式不正确: " + e.getMessage());
                    }
                }
            }
            
            config.setConfigName((String) params.get("configName"));
            config.setConfigCode((String) params.get("configCode"));
            
            // 正确处理设备类型ID的类型转换
            Object equipmentTypeIdObj = params.get("equipmentTypeId");
            if (equipmentTypeIdObj != null) {
                if (equipmentTypeIdObj instanceof Integer) {
                    config.setEquipmentTypeId(((Integer) equipmentTypeIdObj).longValue());
                } else if (equipmentTypeIdObj instanceof Long) {
                    config.setEquipmentTypeId((Long) equipmentTypeIdObj);
                } else if (equipmentTypeIdObj instanceof String) {
                    try {
                        config.setEquipmentTypeId(Long.parseLong((String) equipmentTypeIdObj));
                    } catch (NumberFormatException e) {
                        return error("设备类型ID格式不正确: " + e.getMessage());
                    }
                }
            }
            
            config.setUpdateBy(SecurityUtils.getUsername());
            config.setRemark((String) params.get("remark"));
            
            // 更新巡检配置
            int result = sbInspectionConfigService.updateSbInspectionConfig(config);
            if (result <= 0) {
                return error("修改巡检配置失败");
            }
            
            // 处理巡检项信息
            List<Map<String, Object>> itemMaps = (List<Map<String, Object>>) params.get("items");
            if (itemMaps != null) {
                List<SbInspectionItem> items = new java.util.ArrayList<>();
                
                for (Map<String, Object> itemMap : itemMaps) {
                    SbInspectionItem item = new SbInspectionItem();
                    item.setItemName((String) itemMap.get("itemName"));
                    item.setItemStandard((String) itemMap.get("itemStandard"));
                    item.setRequireImage((String) itemMap.get("requireImage"));
                    items.add(item);
                }
                
                // 批量保存巡检项
                sbInspectionItemService.batchSaveInspectionItems(config.getConfigId(), items, config.getUpdateBy());
            }
            
            return success();
        } catch (Exception e) {
            e.printStackTrace();
            return error("修改巡检配置失败：" + e.getMessage());
        }
    }

    /**
     * 删除巡检配置
     */
	@DeleteMapping("/{configIds}")
    public AjaxResult remove(@PathVariable Long[] configIds)
    {
        return toAjax(sbInspectionConfigService.deleteSbInspectionConfigByConfigIds(configIds));
    }

    /**
     * 校验配置编码
     */
    @PostMapping("/checkConfigCodeUnique")
    public AjaxResult checkConfigCodeUnique(@RequestBody SbInspectionConfig sbInspectionConfig)
    {
        return AjaxResult.success(sbInspectionConfigService.checkConfigCodeUnique(sbInspectionConfig));
    }

    /**
     * 巡检配置导入模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<SbInspectionConfig> util = new ExcelUtil<SbInspectionConfig>(SbInspectionConfig.class);
        util.importTemplateExcel(response, "巡检配置数据");
    }

    /**
     * 巡检配置数据导入
     */
    @RequiresPermissions("sb:inspectionConfig:import")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<SbInspectionConfig> util = new ExcelUtil<SbInspectionConfig>(SbInspectionConfig.class);
        List<SbInspectionConfig> configList = util.importExcel(file.getInputStream());
        String operName = SecurityUtils.getUsername();
        String message = sbInspectionConfigService.importInspectionConfig(configList, updateSupport, operName);
        return success(message);
    }

    /**
     * 根据配置编码获取巡检配置信息
     */
    @GetMapping("/getByCode/{configCode}")
    public AjaxResult getConfigByCode(@PathVariable String configCode)
    {
        SbInspectionConfig config = sbInspectionConfigService.selectSbInspectionConfigByConfigCode(configCode);
        return success(config);
    }

    /**
     * 根据设备类型ID查询巡检配置
     */
    @GetMapping("/type/{equipmentTypeId}")
    public AjaxResult listByEquipmentTypeId(@PathVariable("equipmentTypeId") Long equipmentTypeId)
    {
        List<SbInspectionConfig> list = sbInspectionConfigService.selectSbInspectionConfigByEquipmentTypeId(equipmentTypeId);
        return AjaxResult.success(list);
    }

    /**
     * 生成配置编码
     */
    @GetMapping("/generateConfigCode")
    public AjaxResult generateConfigCode()
    {
        return AjaxResult.success(sbInspectionConfigService.generateConfigCode());
    }
    
    /**
     * 修改巡检配置状态
     */
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SbInspectionConfig sbInspectionConfig)
    {
        sbInspectionConfig.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(sbInspectionConfigService.updateSbInspectionConfig(sbInspectionConfig));
    }
} 